# Copyright (C) 2015-2021, Wazuh Inc.
# Created by Wazuh, Inc. <info@wazuh.com>.
# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2

import logging

from wazuh.core import common
from wazuh.core.vulnerability import WazuhDBQueryVulnerability
from wazuh.core.results import AffectedItemsWazuhResult
from wazuh.rbac.decorators import expose_resources

logger = logging.getLogger('wazuh')


@expose_resources(actions=["vulnerability:read"], resources=["agent:id:{agent_list}"], post_proc_func=None)
def get_agent_cve(agent_list=None, offset=0, limit=common.database_limit, sort=None, search=None, select=None, q='',
                  distinct=None, filters=None):
    """Get agents' vulnerabilities.

    Parameters
    ----------
    agent_list : list
        List of agents ID's.
    offset : int
        First item to return.
    limit : int
        Maximum number of items to return.
    sort : str
        Sort the collection by a field or fields (separated by comma). Use +/- at the beginning to list in
        ascending or descending order.
    search : str
        Look for elements with the specified string.
    select : list
        Fields to return.
    q : str
        Query to filter results by.
    distinct : bool
        Look for distinct values.
    filters : dict
        Fields to filter by.

    Returns
    -------
    result : AffectedItemsWazuhResult
        JSON containing the vulnerabilities.
    """
    result = AffectedItemsWazuhResult(all_msg='All selected vulnerabilities were returned',
                                      some_msg='Some vulnerabilities were not returned',
                                      none_msg='No vulnerabilities were returned'
                                      )

    with WazuhDBQueryVulnerability(agent_id=agent_list[0], offset=offset, limit=limit, sort=sort, search=search,
                                   select=select, query=q, filters=filters, count=True, get_data=True,
                                   distinct=distinct) as db_query:
        data = db_query.run()

    result.affected_items.extend(data['items'])
    result.total_affected_items = data['totalItems']

    return result
